package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.LoginReq;
import com.ydkj.a37e_mall.Classes.Model.Request.OauthloginReq;
import com.ydkj.a37e_mall.Classes.Model.Response.LoginResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_post;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.OnLoginListener;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cz.msebera.android.httpclient.Header;


/**
 * Created by Administrator on 2017/1/9.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener, PlatformActionListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private EditText et_account_number, et_password;
    private TextView tv_login;
    private TextView tv_quick_register, tv_forget_password;
    private ImageView img_back;
    private String secret;


    private LinearLayout lly_qq, lly_weixin, lly_weibo;//第三方登录
    private static final int MSG_SMSSDK_CALLBACK = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;
    private Handler handler;
    private OnLoginListener signupListener;

    private String openId;
    private String name;
    private String icon;
    private int type; //1为微信,2为微博,3为qq

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_AUTH_CANCEL: {
                        Log.e("ssss", "取消授权");

                        //取消授权
                        Toast.makeText(mActivity, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case MSG_AUTH_ERROR: {
                        Log.e("ssss", "授权失败");

                        //授权失败
                        Toast.makeText(mActivity, R.string.auth_error, Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case MSG_AUTH_COMPLETE: {
                        Log.e("ssss", "授权成功");
                        //授权成功
                        Toast.makeText(mActivity, R.string.auth_complete, Toast.LENGTH_SHORT).show();
                        Object[] objs = (Object[]) msg.obj;
                        String platform = (String) objs[0];
                        HashMap<String, Object> res = (HashMap<String, Object>) objs[1];

                        Log.e("ssss", "platform==》" + platform);
                        if (platform.equals("QQ")) {
                            QQ qq = new QQ(mActivity);
                            openId = qq.getDb().getUserId();
                            icon = qq.getDb().getUserIcon();
                            name = qq.getDb().getUserName();
                            Log.e("ssss", "qqopenId==》" + openId);
                            Log.e("ssss", "qqopenicon==》" + icon);
                            Log.e("ssss", "qqopenname==》" + name);
                        }
                        if (platform.equals("Wechat")) {
                            Wechat weixin = new Wechat(mActivity);

                            openId = weixin.getDb().getUserId();
                            icon = weixin.getDb().getUserIcon();
                            name = weixin.getDb().getUserName();
                            Log.e("ssss", "weixinqqopenId==》" + openId);
                            Log.e("ssss", "weixinqqopenicon==》" + icon);
                            Log.e("ssss", "weixinqqopenname==》" + name);
                        }
                        if (platform.equals("SinaWeibo")) {
                            SinaWeibo sina = new SinaWeibo(mActivity);
                            openId = sina.getDb().getUserId();
                            icon = sina.getDb().getUserIcon();
                            name = sina.getDb().getUserName();
                            Log.e("ssss", "sinaqqopenId==》" + openId);
                            Log.e("ssss", "sinaqqopenicon==》" + icon);
                            Log.e("ssss", "sinaqqopenname==》" + name);
                        }

                        Oauth_login(type);
                    }
                    break;
                    case MSG_SMSSDK_CALLBACK: {
//                if (msg.arg2 == SMSSDK.RESULT_ERROR) {
//                    Toast.makeText(mActivity, "操作失败", Toast.LENGTH_SHORT).show();
//                } else {
//                    switch (msg.arg1) {
//                        case SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE: {
//                            if (msgLoginDlg != null && msgLoginDlg.isShowing()) {
//                                msgLoginDlg.dismiss();
//                            }
//                            Toast.makeText(mActivity, "提交验证码成功", Toast.LENGTH_SHORT).show();
//                            Message m = new Message();
//                            m.what = MSG_AUTH_COMPLETE;
//                            m.obj = new Object[]{"SMSSDK", (HashMap<String, Object>) msg.obj};
//                            handler.sendMessage(m);
//                        }
//                        break;
//                        case SMSSDK.EVENT_GET_VERIFICATION_CODE: {
//                            Toast.makeText(mActivity, "验证码已经发送", Toast.LENGTH_SHORT).show();
//                        }
//                        break;
//                    }
//                }
                    }
                    break;
                }
            }
        };

        setContentView(R.layout.login);
        mActivity = this;
        ShareSDK.initSDK(mActivity);

        init();
//        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {
        myApplication = MyApplication.getInstance();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        et_account_number = (EditText) mActivity.findViewById(R.id.et_account_number);
        et_password = (EditText) mActivity.findViewById(R.id.et_password);
        tv_quick_register = (TextView) mActivity.findViewById(R.id.tv_quick_register);
        tv_forget_password = (TextView) mActivity.findViewById(R.id.tv_forget_password);
        tv_login = (TextView) mActivity.findViewById(R.id.tv_login);
        lly_qq = (LinearLayout) mActivity.findViewById(R.id.lly_qq);
        lly_weixin = (LinearLayout) mActivity.findViewById(R.id.lly_weixin);
        lly_weibo = (LinearLayout) mActivity.findViewById(R.id.lly_weibo);


        tv_login.setOnClickListener(this);
        tv_quick_register.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);
        img_back.setOnClickListener(this);
        lly_qq.setOnClickListener(this);
        lly_weixin.setOnClickListener(this);
        lly_weibo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login: //登录
                Login();

                break;
            case R.id.tv_quick_register://注册
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));

                break;
            case R.id.tv_forget_password://忘记密码
                startActivity(new Intent(LoginActivity.this, ForgetPassWord.class));

                break;
            case R.id.img_back://返回
                Intent intent = new Intent();
                setResult(RESULT_CANCELED, intent);
                finish();
                break;

            case R.id.lly_qq:
                //QQ空间
                Platform qzone = ShareSDK.getPlatform(QQ.NAME);
                type = 3;
                authorize(qzone);
                break;
            case R.id.lly_weixin:
                //微信登录
                //测试时，需要打包签名；sample测试时，用项目里面的demokey.keystore
                //打包签名apk,然后才能产生微信的登录
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);

                if (!wechat.isClientValid()) {
                    Toast.makeText(mActivity, "微信未安装,请先安装微信", Toast.LENGTH_LONG).show();
                    return;
                }
                type = 1;
                authorize(wechat);
                break;
            case R.id.lly_weibo:
                //新浪微博
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                type = 2;
                authorize(sina);
                break;
        }
    }

    //登录
    private void Login() {
        CustomProgressDialog.createDialog(mActivity).Show();
        LoginReq req = new LoginReq();
        req.setMobile(et_account_number.getText().toString());
        req.setPassword(et_password.getText().toString());
        if (!myApplication.getChannelID().equals("")) {
            req.setAlias(myApplication.getChannelID());
        }
        req.setDevice_type(3);
        String url = Const.COMMON_ADDRESS + req.urlString();
        RequestParams params = new RequestParams();

        try {
            String source = req.getString();
            Log.e("ssss", "source==>" + source);
            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("secret", secret);
        Log.e("url", "secret==" + secret);
        Log.e("url", "params==" + params);

        Async_http_post.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                Log.e("url", "login_json==" + response);
                if (errno.equals("000")) {
                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                    sharedPreferencesUtil.setUsername(et_account_number.getText().toString().trim());
                    sharedPreferencesUtil.setPassword(et_password.getText().toString());
                    Log.e("url", "login_AccessToken==" + resp.getResult().getAccess_token());
                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    sharedPreferencesUtil.setUSERID(resp.getResult().getData().getId() + "");
                    myApplication.setDataEntity(resp.getResult().getData());

                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
//                    CommonUtil.showToast(mActivity, errmag);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    //第三方登录
    private void Oauth_login(final int type) {
        CustomProgressDialog.createDialog(mActivity).show();
        OauthloginReq req = new OauthloginReq();
        req.setOpenid(openId);
        req.setType(type + "");
        req.setAlias(myApplication.getChannelID());
        req.setDevice_type("3");
        req.setNickname(name);
        req.setAvatar(icon);
        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());

        Async_http_post.post(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmag = response.optString("errmsg");
                Log.e("url", "第三方==" + response);
                if (errno.equals("000")) {
                    LoginResp resp = GsonImpl.get().toObject(response.toString(), LoginResp.class);
                    CommonUtil.showToast(mActivity, errmag);
                    sharedPreferencesUtil.setOpen_id(openId);
                    sharedPreferencesUtil.setType(type + "");
                    sharedPreferencesUtil.setNickname(name);
                    sharedPreferencesUtil.setAvatar(icon);
                    Log.e("url", "login_AccessToken==" + resp.getResult().getAccess_token());
                    sharedPreferencesUtil.setAccessToken(resp.getResult().getAccess_token());
                    sharedPreferencesUtil.setUSERID(resp.getResult().getData().getId() + "");
                    myApplication.setDataEntity(resp.getResult().getData());

                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });

    }

    //执行授权,获取用户信息
    //文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
    private void authorize(Platform plat) {
//        CustomProgressDialog.createDialog(mActivity).show();
        if (plat == null) {
//            popupOthers();
            return;
        }

        Log.e("ssss", "第三方登录==》" + plat + "");
        plat.setPlatformActionListener(this);
        //关闭SSO授权
        plat.SSOSetting(true);
        plat.showUser(null);
    }


    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Log.e("ssss", "111111");
        Log.e("ssss", "platform===>" + platform);
        Log.e("ssss", "iiiii===>" + action);
        Log.e("ssss", "res===>" + res);
        if (action == Platform.ACTION_USER_INFOR) {
            Log.e("ssss", "hander");
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[]{platform.getName(), res};
            handler.sendMessage(msg);
        }
    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        Log.e("ssss", "222222");

        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        t.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        Log.e("ssss", "33333");

        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }

    /**
     * 设置授权回调，用于判断是否进入注册
     */
    public void setOnLoginListener(OnLoginListener l) {
        this.signupListener = l;
    }
}
